import os
import re
import hashlib
import requests
from bs4 import BeautifulSoup
import tkinter as tk
from tkinter import messagebox
from tkinter.ttk import Progressbar, Style
import threading

# 下载文件保存的目录，只在用户点击导出时创建
def get_new_download_dir():
    index = 1
    while True:
        # current_download_dir = f'./微信_gif导出_{index}'
        current_download_dir = f'./微信_gif导出_{index}'
        if not os.path.exists(current_download_dir):
            os.makedirs(current_download_dir)
            return current_download_dir
        index += 1

def get_safe_filename(url):
    # 使用哈希函数生成文件名，避免非法字符
    url_hash = hashlib.md5(url.encode()).hexdigest()
    return f'{url_hash}.file'

def export_gifs(progress_var, progress_bar, export_button, terminate_button, progress_label):
    global stop_event

    # 查找当前目录下所有 .html 文件
    html_files = [f for f in os.listdir('.') if f.endswith('.html')]

    # 查找匹配的URL并进行去重
    all_matches = set()  # 使用集合去重

    for html_file in html_files:
        # 读取每个HTML文件内容
        with open(html_file, 'r', encoding='utf-8') as file:
            content = file.read()

        # 使用BeautifulSoup解析HTML
        soup = BeautifulSoup(content, 'html.parser')

        # 查找包含JavaScript的<script>标签
        script_tags = soup.find_all('script')

        # 提取包含特定数据的URL
        for script in script_tags:
            # 先检查script.string是否为None
            if script.string and 'const chatMessages' in script.string:
                # 提取所有text字段内容
                text_matches = re.findall(r'"text":\s*"(http[^"]+)"', script.string)
                all_matches.update(text_matches)  # 将结果添加到集合中，自动去重

    total_files = len(all_matches)
    if total_files == 0:
        messagebox.showinfo("完成", "未找到可导出表情包。")
        return

    # 更新进度条最大值
    progress_var.set(0)
    progress_bar["maximum"] = total_files

    for i, url in enumerate(all_matches, 1):
        if stop_event.is_set():
            break

        # 生成安全的文件名
        original_filename = get_safe_filename(url)
        original_file_path = os.path.join(download_dir, original_filename)
        new_file_path = os.path.splitext(original_file_path)[0] + '.gif'  # 修改后缀为 .gif

        # 如果文件已经存在，跳过下载
        if os.path.exists(new_file_path):
            progress_var.set(i)
            progress_label.config(text=f"{i}/{total_files}")
            progress_bar.update()
            continue

        # 下载文件
        response = requests.get(url, stream=True)
        if response.status_code == 200:
            with open(original_file_path, 'wb') as file:
                for chunk in response.iter_content(chunk_size=8192):
                    if chunk:
                        file.write(chunk)
            # 下载完成后重命名文件为 .gif
            os.rename(original_file_path, new_file_path)
        else:
            print(f'Failed to download {url}')

        # 更新进度条和标签
        progress_var.set(i)
        progress_label.config(text=f"{i}/{total_files}")
        progress_bar.update()

    if stop_event.is_set():
        messagebox.showinfo("终止", "导出已终止。")
    else:
        messagebox.showinfo("完成", "微信表情包导出完成！")

    # 启用导出按钮并禁用终止按钮
    export_button.config(state=tk.NORMAL)
    terminate_button.config(state=tk.DISABLED)

def on_export_button_click():
    global stop_event
    global thread
    global download_dir

    # 如果导出操作正在进行中，直接返回
    if thread and thread.is_alive():
        messagebox.showinfo("提示", "当前操作正在进行中，请先终止操作再重新导出。")
        return

    # 重新设置状态和按钮
    stop_event = threading.Event()  # 创建新的终止事件
    progress_var.set(0)  # 重置进度条
    progress_label.config(text="0/0")  # 重置进度标签
    export_button.config(state=tk.DISABLED)
    terminate_button.config(state=tk.NORMAL)

    # 创建新的下载目录
    download_dir = get_new_download_dir()

    # 启动导出线程
    thread = threading.Thread(target=export_gifs, args=(progress_var, progress_bar, export_button, terminate_button, progress_label))
    thread.start()

def on_terminate_button_click():
    global stop_event

    # 设置导出操作为终止状态
    stop_event.set()

    # 启用导出按钮并禁用终止按钮
    export_button.config(state=tk.NORMAL)
    terminate_button.config(state=tk.DISABLED)

# 初始化全局变量
stop_event = threading.Event()
thread = None

# 创建GUI   //打包命令：pyinstaller --onefile --windowed --icon=微信.ico  main.py
root = tk.Tk()
root.title("聊天窗gif批量提取_需要dd")
# 设置窗口图标（图标必须为 .ico 格式）
root.iconbitmap("2.ico")
# 设置窗体尺寸（宽度x高度）
window_width = 400  # 修改为你需要的宽度
window_height = 200  # 修改为你需要的高度
root.geometry(f"{window_width}x{window_height}")

# 禁用缩放
root.resizable(False, False)

# 创建自定义样式
style = Style()
style.layout('text.Horizontal.TProgressbar',
             [('Horizontal.Progressbar.trough',
               {'children': [('Horizontal.Progressbar.pbar',
                              {'side': 'left', 'sticky': 'ns'})],
                'sticky': 'nswe'}),
              ('Horizontal.Progressbar.label', {'sticky': ''})])
style.configure('text.Horizontal.TProgressbar', text='0/0')

# 创建进度条和进度标签
progress_var = tk.IntVar()
progress_bar = Progressbar(root, variable=progress_var, length=300, mode='determinate', style='text.Horizontal.TProgressbar')
progress_bar.pack(pady=20)

progress_label = tk.Label(root, text="0/0")
progress_label.place(in_=progress_bar, relx=0.5, rely=0.5, anchor='center')

# 创建按钮
export_button = tk.Button(root, text="提取表情包", command=on_export_button_click, padx=20, pady=10)
export_button.pack(pady=20)

terminate_button = tk.Button(root, text="终止", command=on_terminate_button_click, padx=20, pady=10, state=tk.DISABLED)
terminate_button.pack(pady=10)

root.mainloop()
